package cn.taketoday.live.file;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

import cn.taketoday.live.config.GlobalData;
import cn.taketoday.live.utils.FileUtils;

/**
 * @author BanqiJane
 */
public class GuardFileTools {
  public static Map<Long, String> read() throws IOException {
    Map<Long, String> hashtable = new HashMap<>();
    String path = FileUtils.getApplicationPath();
    path = path + "/guardFile/";
    File file = new File(path);
    file.setWritable(true, false);
    if (!file.exists()) {
      file.mkdirs();
    }
    file = new File(path + "/guards(" + GlobalData.ROOM_ID + ")" + ".txt");
    file.setWritable(true, false);
    if (!file.exists())
      file.createNewFile();
    try (BufferedReader bufReader = new BufferedReader(new FileReader(file))) {
      String s;
      while ((s = bufReader.readLine()) != null) {
        String[] str = s.split(",");
        hashtable.put(Long.valueOf(str[0]), str[1]);
      }
    }
    return hashtable;
  }

  public static void write(String msg) throws IOException {
    String path = FileUtils.getApplicationPath();
    // 如果文件存在，则追加内容；如果文件不存在，则创建文件
    path = path + "/guardFile/";
    File file = new File(path);
    file.setWritable(true, false);
    if (!file.exists())
      file.mkdirs();
    file = new File(path + "guards(" + GlobalData.ROOM_ID + ")" + ".txt");
    file.setWritable(true, false);
    if (!file.exists()) {
      file.createNewFile();
    }

    try (FileWriter fw = new FileWriter(file, true);
            PrintWriter pw = new PrintWriter(fw)) {

      pw.println(msg);
      pw.flush();
      fw.flush();
    }
  }
}
